package com.apply.config.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tianp
 */
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private SidAuthInterceptor sidAuthInterceptor;
    @Value("${image.path}")
    private String path;
    private static final String ALL = "/**";
    private String SID_PATH = "/private/**";
    private String[] SWAGGER_PATH = {"/swagger-resources/**", "/v2/api-docs"};
    private String[] PUB = {"/private/user/pub/**"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/img/**")
                .addResourceLocations("file:" + path);
        super.addResourceHandlers(registry);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //CORS
        List<String> accessAllowedFrom = new ArrayList<>();
        accessAllowedFrom.add("localhost");
        accessAllowedFrom.add("127\\.0\\.0\\.1");
        accessAllowedFrom.add("47\\.104\\.150\\.\\d{0,3}");
        accessAllowedFrom.add("10\\.10\\.20\\.\\d{0,255}");
        CORSInterceptor corsInterceptor = new CORSInterceptor(accessAllowedFrom);
        registry.addInterceptor(corsInterceptor).addPathPatterns(ALL);
        //  测试取消
        InterceptorRegistration sidInterceptor = registry.addInterceptor(sidAuthInterceptor);
        sidInterceptor.addPathPatterns(SID_PATH);
        sidInterceptor.excludePathPatterns(PUB).excludePathPatterns(SWAGGER_PATH);
        super.addInterceptors(registry);
    }
}
